package com.hnu.store.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnu.store.dto.NftDTO;
import com.hnu.store.dto.SaleDTO;
import com.hnu.store.entity.Sale;
import com.hnu.store.entity.Trade;
import com.hnu.store.entity.User;
import com.hnu.store.entity.Work;
import com.hnu.store.mapper.SaleMapper;
import com.hnu.store.mapper.TradeMapper;
import com.hnu.store.mapper.UserMapper;
import com.hnu.store.mapper.WorkMapper;
import com.hnu.store.service.ISaleService;
import com.hnu.store.service.ex.ChangeSaleException;
import com.hnu.store.service.ex.FileNotFoundException;
import com.hnu.store.service.ex.NftListException;
import com.hnu.store.service.ex.ServiceException;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class SaleServiceImpl implements ISaleService {

  @Autowired
  public SaleMapper saleMapper;

  @Autowired
  public WorkMapper workMapper;

  @Autowired
  public UserMapper userMapper;

  @Autowired
  public TradeMapper tradeMapper;

  @Autowired
  public StringRedisTemplate redisTemplate;

  @Override
  public SaleDTO getSaleById(Integer saleId) {
    Sale sale = saleMapper.getSaleById(saleId);
    User user = userMapper.findById(sale.getUserId());
    Work work = workMapper.getWorkById(sale.getWorkId());
    String status;
    switch (sale.getStatus()) {
      case 0:
        status = "停售";
        break;
      case 1:
        status = "使用权";
        break;
      case 2:
        status = "所有权";
        break;
      case 3:
        status = "所有权已转让";
        break;
      default:
        status = "出错了";
        break;
    }
    String type;
    switch (work.getType()) {
      case 1:
        type = "摄影作品";
        break;
      case 2:
        type = "文字作品";
        break;
      case 3:
        type = "影视作品";
        break;
      case 4:
        type = "音乐作品";
        break;
      case 5:
        type = "美术作品";
        break;
      default:
        throw new ServiceException("作品类型错误");
    }

    String chainHash = work.getChainHash();
    return new SaleDTO(saleId,sale.getUserId(),sale.getTitle(), status, sale.getPrice(),
        sale.getPicture(), sale.getDescription(), work.getWorkTag1(), work.getWorkTag2(),
        work.getWorkTag3(), work.getFileName(), work.getWorkName(), work.getBlockHeight(),
        work.getChainTime(), work.getFileHash(), user.getCitizenId(),sale.getAuthorizeNum(),
        user.getRealName(),type,chainHash);
  }

  @Override
  public List<SaleDTO> getSaleListById(Integer userId, String stringPara, String status) {
    ArrayList<SaleDTO> saleDtoList = new ArrayList<>();
    List<Sale> saleList = saleMapper.getSaleListByUserId(userId);
    for (Sale it : saleList) {
      if(it.getStatus()==3) {
        continue;
      }
      //  如果搜索条件不为空且不匹配则跳过
      if (!stringPara.equals("")&&!it.getTitle().contains(stringPara)) {
        continue;
      }
      SaleDTO item = new SaleDTO();
      item.setId(it.getId());
      item.setTitle(it.getTitle());
      item.setPrice(it.getPrice());
      switch (it.getStatus()) {
        case 0:
          item.setStatus("停售");
          break;
        case 1:
          item.setStatus("使用权");
          break;
        case 2:
          item.setStatus("所有权");
          break;
        case 3:
          item.setStatus("所有权已转让");
          break;
        default:
          item.setStatus("出错了");
          break;
      }
      //  如果售单的status不为空且不匹配则跳过
      if (!status.equals("")&&!item.getStatus().equals(status)) {
        continue;
      }
      User user = userMapper.findById(it.getUserId());
      Work work = workMapper.getWorkById(it.getWorkId());

      String type;
      switch (work.getType()) {
        case 1:
          type = "摄影作品";
          break;
        case 2:
          type = "文字作品";
          break;
        case 3:
          type = "影视作品";
          break;
        case 4:
          type = "音乐作品";
          break;
        case 5:
          type = "美术作品";
          break;
        default:
          throw new ServiceException("作品类型错误");
      }
      item.setUserId(userId);
      //  设置商品的类型
      item.setType(type);
      item.setAuthorizeNum(it.getAuthorizeNum());
      //  设置标签
      item.setTag1(work.getWorkTag1());
      item.setTag2(work.getWorkTag2());
      item.setTag3(work.getWorkTag3());
      //  设置作品名称
      item.setNftName(work.getWorkName());
      item.setPicture(it.getPicture());
      item.setDescription(it.getDescription());
      //  缺少补齐
      item.setRealName(user.getRealName());
      item.setFileName(work.getFileName());
      item.setFileHash(work.getFileHash());
      item.setChainTime(work.getChainTime());
      item.setBlockHeight(work.getBlockHeight());
      item.setOwnerId(user.getCitizenId());
      saleDtoList.add(item);
    }
    return saleDtoList;
  }

  @Override
  public List<SaleDTO> getAllSaleList() {
    ArrayList<SaleDTO> saleDtoList = new ArrayList<>();
    List<Sale> saleList = saleMapper.getAllSale();
    for (Sale it : saleList) {
      SaleDTO item = new SaleDTO();
      item.setId(it.getId());
      item.setTitle(it.getTitle());
      item.setPrice(it.getPrice());
      item.setPicture(it.getPicture());
      item.setAuthorizeNum(it.getAuthorizeNum());
      Integer status = it.getStatus();
      //  跳过该项不加入dtoList,停售的和所有权转让的不加入商城
      if (status == 0 || status == 3) {
        continue;
      }
      switch (status) {
        case 1:
          item.setStatus("使用权");
          break;
        case 2:
          item.setStatus("所有权");
          break;
        default:
          item.setStatus("出错了");
          break;
      }
      User user = userMapper.findById(it.getUserId());
      Work work = workMapper.getWorkById(it.getWorkId());
      String type;
      switch (work.getType()) {
        case 1:
          type = "摄影作品";
          break;
        case 2:
          type = "文字作品";
          break;
        case 3:
          type = "影视作品";
          break;
        case 4:
          type = "音乐作品";
          break;
        case 5:
          type = "美术作品";
          break;
        default:
          throw new ServiceException("作品类型错误");
      }
      //  设置商品的类型
      item.setType(type);

      //  设置标签
      item.setTag1(work.getWorkTag1());
      item.setTag2(work.getWorkTag2());
      item.setTag3(work.getWorkTag3());
      //  设置作品名称
      item.setNftName(work.getWorkName());
      item.setPicture(it.getPicture());
      item.setDescription(it.getDescription());
      //  缺少补齐
      item.setRealName(user.getRealName());
      item.setFileName(work.getFileName());
      item.setFileHash(work.getFileHash());
      item.setChainTime(work.getChainTime());
      item.setBlockHeight(work.getBlockHeight());
      item.setOwnerId(user.getCitizenId());
      saleDtoList.add(item);
    }
    return saleDtoList;
  }

  @Override
  public void getImg(String filePath, String fileName, HttpServletResponse response) {
    //  根据文件路径获取封面文件
    File file = new File(filePath + File.separator + fileName);
    if (!file.exists()) {
      throw new FileNotFoundException("http请求的文件不存在");
    }
    //  配置文件下载
    response.setHeader("content-type", "application/octet-stream");
    response.setContentType("application/octet-stream");
    // 下载文件能正常显示中文
    try {
      response.setHeader("Content-Disposition",
          "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      System.out.println("getImg获得封面过程中encode失败");
      e.printStackTrace();
    }
    // 实现文件下载
    byte[] buffer = new byte[1024];
    try {
      FileInputStream fis = new FileInputStream(file);
      OutputStream os = response.getOutputStream();
      while ((fis.read(buffer)) != -1) {
        os.write(buffer);
        os.flush();
      }
      os.close();
    } catch (Exception e) {
      System.out.println("写入HttpServletResponse错误" + e);
      e.printStackTrace();
    }
  }

  @Override
  public void addSale(Sale sale) {
    Work work = workMapper.getWorkById(sale.getWorkId());
    sale.setAuthorizeNum(0);
    Date date = new Date();
    sale.setCreatedTime(date);
    sale.setModifiedTime(date);
    System.out.println(sale.getUserId());
    Integer userId = sale.getUserId();
    User user = userMapper.findById(userId);
    System.out.println(user);
    String owner = user.getUsername();
    sale.setCreatedUser(owner);
    sale.setModifiedUser(owner);
    //  设置封面
    Integer type = work.getType();
    //  摄影作品或者美术作品，返回图片，否则返回默认封面
    if (type == 1 || type == 5) {
      try {
        sale.setPicture("http://124.222.70.223:8081/sale/getImg?filePath=" + URLDecoder.decode(
            work.getFileLocation(), "UTF-8") + "&fileName=" + work.getFileName());
      } catch (UnsupportedEncodingException e) {
        System.out.println("addSale生成封面时decode发生错误");
        throw new RuntimeException(e);
      }
    } else if (type == 2) {
      //  文字作品
      sale.setPicture(
          "http://124.222.70.223:8081/sale/getImg?filePath=" + System.getProperty("user.dir")
              + File.separator + "defaultImg" + "&fileName=text.png");

    } else if (type == 3) {
      //  影视作品
      sale.setPicture(
          "http://124.222.70.223:8081/sale/getImg?filePath=" + System.getProperty("user.dir")
              + File.separator + "defaultImg" + "&fileName=video.png");

    } else if (type == 4) {
      //  音乐作品
      sale.setPicture(
          "http://124.222.70.223:8081/sale/getImg?filePath=" + System.getProperty("user.dir")
              + File.separator + "defaultImg" + "&fileName=music.png");

    }
    saleMapper.addSale(sale);

    //  判断出售类型，若为使用权则添加至redis缓存
    if(sale.getStatus()==1) {
      String key = "sale:" + sale.getId();
      ObjectMapper objectMapper = new ObjectMapper();
      try {
        String json = objectMapper.writeValueAsString(sale);
        redisTemplate.opsForValue().set(key, json);
      } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
      }
    }
  }

  @Override
  public Sale changeStatus(Integer id, Integer status) {
    Sale sale = saleMapper.getSaleById(id);
    sale.setStatus(status);
    if (saleMapper.update(sale) != 1) {
      throw new ChangeSaleException("修改售单状态失败");
    }
    //  返回更新后的sale
    return saleMapper.getSaleById(id);
  }

  @Override
  public List<NftDTO> getNftList(Integer userId) {
    List<Work> workList = workMapper.getListByUserId(userId);
    if (workList.isEmpty()) {
      throw new NftListException("用户无作品");
    }
    //  创建dtoList
    ArrayList<NftDTO> nftList = new ArrayList<>();
    for (Work it : workList) {

      Sale sale = saleMapper.getSaleByWorkId(it.getId());
      //  代表已经在售,跳过,不可以添加出售
      if (sale != null) {
        continue;
      }
      //  未上链的,跳过,不可以添加出售
      if (it.getStatus() == 0) {
        continue;
      }

      NftDTO item = new NftDTO();
      item.setName(it.getWorkName());
      item.setId(it.getId());
      switch (it.getStatus()) {
        case 0:
          item.setStatus("未存证");
          break;
        case 1:
          item.setStatus("已存证");
          break;
        default:
          item.setStatus("错误");
          break;
      }

      switch (it.getType()) {
        case 1:
          item.setType("摄影作品");
          break;
        case 2:
          item.setType("文字作品");
          break;
        case 3:
          item.setType("影视作品");
          break;
        case 4:
          item.setType("音乐作品");
          break;
        case 5:
          item.setType("美术作品");
          break;
        default:
          item.setType("未设定");
          break;
      }

      item.setCreatedTime(it.getCreatedTime());
      item.setTag1(it.getWorkTag1());
      item.setTag2(it.getWorkTag2());
      item.setTag3(it.getWorkTag3());
      nftList.add(item);
    }
    return nftList;
  }

  @Override
  public void deleteSale(Integer id) {
    saleMapper.delete(id);
  }

  @Override
  public void editSale(Sale sale) {
    Sale oldSale = saleMapper.getSaleById(sale.getId());
    oldSale.setPrice(sale.getPrice());
    oldSale.setDescription(sale.getDescription());
    oldSale.setTitle(sale.getTitle());
    oldSale.setModifiedTime(new Date());
    int rows = saleMapper.update(oldSale);
    if(rows!=1) {
      throw new ChangeSaleException("修改售单信息失败");
    }
  }

  @Override
  public List<SaleDTO> adminGetAllSale() {

    ArrayList<SaleDTO> saleDtoList = new ArrayList<>();
    List<Sale> saleList = saleMapper.getAllSale();
    for (Sale it : saleList) {
      SaleDTO item = new SaleDTO();
      item.setId(it.getId());
      item.setTitle(it.getTitle());
      item.setPrice(it.getPrice());
      item.setPicture(it.getPicture());
      item.setAuthorizeNum(it.getAuthorizeNum());
      Integer status = it.getStatus();
      //  所有权转让的不展示给管理员，展示停售的
      if(status==3) {
        continue;
      }

      switch (status) {
        case 0:
          item.setStatus("停售");
          break;
        case 1:
          item.setStatus("使用权");
          break;
        case 2:
          item.setStatus("所有权");
          break;
        default:
          item.setStatus("出错了");
          break;
      }
      User user = userMapper.findById(it.getUserId());
      Work work = workMapper.getWorkById(it.getWorkId());
      String type;
      switch (work.getType()) {
        case 1:
          type = "摄影作品";
          break;
        case 2:
          type = "文字作品";
          break;
        case 3:
          type = "影视作品";
          break;
        case 4:
          type = "音乐作品";
          break;
        case 5:
          type = "美术作品";
          break;
        default:
          throw new ServiceException("作品类型错误");
      }
      //  设置商品的类型
      item.setType(type);

      //  设置标签
      item.setTag1(work.getWorkTag1());
      item.setTag2(work.getWorkTag2());
      item.setTag3(work.getWorkTag3());
      //  设置作品名称
      item.setNftName(work.getWorkName());
      item.setPicture(it.getPicture());
      item.setDescription(it.getDescription());
      //  缺少补齐
      item.setRealName(user.getRealName());
      item.setFileName(work.getFileName());
      item.setFileHash(work.getFileHash());
      item.setChainTime(work.getChainTime());
      item.setBlockHeight(work.getBlockHeight());
      item.setOwnerId(user.getCitizenId());
      saleDtoList.add(item);
    }
    return saleDtoList;
  }

  @Override
  public List<SaleDTO> getSaleByGoodsType(Integer id,String goodsType) {
    ArrayList<SaleDTO> saleDtoList = new ArrayList<>();

    int type;
    //  根据筛选类别设置type
    switch (goodsType) {
      case "摄影作品":
        type = 1;
        break;
      case "文字作品":
        type = 2;
        break;
      case "影视作品":
        type = 3;
        break;
      case "音乐作品":
        type = 4;
        break;
      case "美术作品":
        type = 5;
        break;
      default:
        type = 0;
        break;
    }
    //  根据type获取saleList
    List<Sale> saleList = saleMapper.getSaleByGoodsType(type);

    for (Sale it : saleList) {
      SaleDTO item = new SaleDTO();
      item.setId(it.getId());
      item.setTitle(it.getTitle());
      item.setPrice(it.getPrice());
      item.setPicture(it.getPicture());
      item.setAuthorizeNum(it.getAuthorizeNum());
      Integer status = it.getStatus();

//  跳过该项不加入dtoList,停售的和所有权转让的不加入商城
      if (status == 0 || status == 3) {
        continue;
      }
      //  根据用户id查找交易列表中它买过的商品
      List<Trade> tradeList = tradeMapper.getBuyTrade(id);
      boolean tradeFlag = true;
      for (Trade trade:tradeList) {
        //  买过商品的id和当前商品id相同
        if(trade.getSaleId().equals(it.getId())) {
          tradeFlag = false;
          break;
        }
      }
      //  如果买过该商品则跳过
      if(!tradeFlag) {
        continue;
      }
      //  如果是用户本人的商品则跳过
      if(it.getUserId().equals(id)) {
        continue;
      }
      //  否则展示出来
      switch (status) {
        case 1:
          item.setStatus("使用权");
          break;
        case 2:
          item.setStatus("所有权");
          break;
        default:
          item.setStatus("出错了");
          break;
      }

      User user = userMapper.findById(it.getUserId());
      Work work = workMapper.getWorkById(it.getWorkId());

      switch (work.getType()) {
        case 1:
          goodsType = "摄影作品";
          break;
        case 2:
          goodsType = "文字作品";
          break;
        case 3:
          goodsType = "影视作品";
          break;
        case 4:
          goodsType = "音乐作品";
          break;
        case 5:
          goodsType = "美术作品";
          break;
        default:
          throw new ServiceException("作品类型错误");
      }
      //  设置商品的类型
      item.setType(goodsType);

      //  设置标签
      item.setTag1(work.getWorkTag1());
      item.setTag2(work.getWorkTag2());
      item.setTag3(work.getWorkTag3());
      //  设置作品名称
      item.setNftName(work.getWorkName());
      item.setPicture(it.getPicture());
      item.setDescription(it.getDescription());
      //  缺少补齐
      item.setRealName(user.getRealName());
      item.setFileName(work.getFileName());
      item.setFileHash(work.getFileHash());
      item.setChainTime(work.getChainTime());
      item.setBlockHeight(work.getBlockHeight());
      item.setOwnerId(user.getCitizenId());
      saleDtoList.add(item);
    }
    return saleDtoList;
  }

  @Override
  public List<SaleDTO> getSaleBySaleType(Integer id,String saleType) {
    int type = 0;

    //  根据前端选择的使用权或所有权进行筛选
    switch (saleType) {
      case "使用权":
        type = 1;
        break;
      case "所有权":
        type = 2;
        break;
    }
    List<Sale> saleList = saleMapper.getSaleBySaleType(type);
    ArrayList<SaleDTO> saleDtoList = new ArrayList<>();

    for (Sale it : saleList) {
      SaleDTO item = new SaleDTO();
      item.setId(it.getId());
      item.setTitle(it.getTitle());
      item.setPrice(it.getPrice());
      item.setPicture(it.getPicture());
      item.setAuthorizeNum(it.getAuthorizeNum());
      Integer status = it.getStatus();
//  跳过该项不加入dtoList,停售的和所有权转让的不加入商城
      if (status == 0 || status == 3) {
        continue;
      }
      //  根据用户id查找交易列表中它买过的商品
      List<Trade> tradeList = tradeMapper.getBuyTrade(id);
      boolean tradeFlag = true;
      for (Trade trade:tradeList) {
        //  买过商品的id和当前商品id相同
        if(trade.getSaleId().equals(it.getId())) {
          tradeFlag = false;
          break;
        }
      }
      //  如果买过该商品则跳过
      if(!tradeFlag) {
        continue;
      }
      //  如果是用户本人的商品则跳过
      if(it.getUserId().equals(id)) {
        continue;
      }
      //  否则展示出来

      switch (status) {
        case 1:
          item.setStatus("使用权");
          break;
        case 2:
          item.setStatus("所有权");
          break;
        default:
          item.setStatus("出错了");
          break;
      }

      User user = userMapper.findById(it.getUserId());
      Work work = workMapper.getWorkById(it.getWorkId());

      String goodsType;
      switch (work.getType()) {
        case 1:
          goodsType = "摄影作品";
          break;
        case 2:
          goodsType = "文字作品";
          break;
        case 3:
          goodsType = "影视作品";
          break;
        case 4:
          goodsType = "音乐作品";
          break;
        case 5:
          goodsType = "美术作品";
          break;
        default:
          throw new ServiceException("作品类型错误");
      }
      //  设置商品的类型
      item.setType(goodsType);

      //  设置标签
      item.setTag1(work.getWorkTag1());
      item.setTag2(work.getWorkTag2());
      item.setTag3(work.getWorkTag3());
      //  设置作品名称
      item.setNftName(work.getWorkName());
      item.setPicture(it.getPicture());
      item.setDescription(it.getDescription());
      //  缺少补齐
      item.setRealName(user.getRealName());
      item.setFileName(work.getFileName());
      item.setFileHash(work.getFileHash());
      item.setChainTime(work.getChainTime());
      item.setBlockHeight(work.getBlockHeight());
      item.setOwnerId(user.getCitizenId());
      saleDtoList.add(item);
    }
    return saleDtoList;
  }

  @Override
  public List<SaleDTO> search(Integer id,String sortPara) {
    //  根据搜索内容筛选售单列表
    List<Sale> saleList = saleMapper.search(sortPara);

    ArrayList<SaleDTO> saleDtoList = new ArrayList<>();

    for (Sale it : saleList) {
      SaleDTO item = new SaleDTO();
      item.setId(it.getId());
      item.setTitle(it.getTitle());
      item.setPrice(it.getPrice());
      item.setPicture(it.getPicture());
      item.setAuthorizeNum(it.getAuthorizeNum());
      Integer status = it.getStatus();
//  跳过该项不加入dtoList,停售的和所有权转让的不加入商城
      if (status == 0 || status == 3) {
        continue;
      }
      //  根据用户id查找交易列表中它买过的商品
      List<Trade> tradeList = tradeMapper.getBuyTrade(id);
      boolean tradeFlag = true;
      for (Trade trade:tradeList) {
        //  买过商品的id和当前商品id相同
        if(trade.getSaleId().equals(it.getId())) {
          tradeFlag = false;
          break;
        }
      }
      //  如果买过该商品则跳过
      if(!tradeFlag) {
        continue;
      }
      //  如果是用户本人的商品则跳过
      if(it.getUserId().equals(id)) {
        continue;
      }
      //  否则展示出来

      switch (status) {
        case 1:
          item.setStatus("使用权");
          break;
        case 2:
          item.setStatus("所有权");
          break;
        default:
          item.setStatus("出错了");
          break;
      }

      User user = userMapper.findById(it.getUserId());
      Work work = workMapper.getWorkById(it.getWorkId());

      String goodsType;
      switch (work.getType()) {
        case 1:
          goodsType = "摄影作品";
          break;
        case 2:
          goodsType = "文字作品";
          break;
        case 3:
          goodsType = "影视作品";
          break;
        case 4:
          goodsType = "音乐作品";
          break;
        case 5:
          goodsType = "美术作品";
          break;
        default:
          throw new ServiceException("作品类型错误");
      }
      //  设置商品的类型
      item.setType(goodsType);

      //  设置标签
      item.setTag1(work.getWorkTag1());
      item.setTag2(work.getWorkTag2());
      item.setTag3(work.getWorkTag3());
      //  设置作品名称
      item.setNftName(work.getWorkName());
      item.setPicture(it.getPicture());
      item.setDescription(it.getDescription());
      //  缺少补齐
      item.setRealName(user.getRealName());
      item.setFileName(work.getFileName());
      item.setFileHash(work.getFileHash());
      item.setChainTime(work.getChainTime());
      item.setBlockHeight(work.getBlockHeight());
      item.setOwnerId(user.getCitizenId());
      saleDtoList.add(item);
    }
    return saleDtoList;
  }

  @Override
  public List<SaleDTO> post(Integer userId) {
    //  根据用户id获取用户信息（标签）
    User user = userMapper.findById(userId);
    String userTag1 = user.getTag1();
    String userTag2 = user.getTag2();
    String userTag3 = user.getTag3();

    //  获取全部售单
    List<Sale> allSale = saleMapper.getAllSale();
    //  在售售单
    List<Sale> saleList = new ArrayList<>();

    for (Sale it : allSale) {
      //  移除停售和所有权售出
      if(it.getStatus()==0 ||  it.getStatus()==3) {
        continue;
      }

      //  根据用户id查找交易列表中它买过的商品
      List<Trade> tradeList = tradeMapper.getBuyTrade(userId);
      boolean tradeFlag = true;
      for (Trade trade:tradeList) {
        //  买过商品的id和当前商品id相同
        if(trade.getSaleId().equals(it.getId())) {
          tradeFlag = false;
          break;
        }
      }
      //  如果买过该商品则跳过
      if(!tradeFlag) {
        continue;
      }
      //  如果是用户本人的商品则跳过
      if(it.getUserId().equals(userId)) {
        continue;
      }
      saleList.add(it);
    }


    //  添加两个售单到list
    List<Sale> listForReturn = new ArrayList<>();
    Random random = new Random();
    int temp = random.nextInt(saleList.size());
    listForReturn.add(saleList.get(temp));
    int another;
    while ((another=random.nextInt(saleList.size()))==temp) {

    }
    listForReturn.add(saleList.get(another));

    //  遍历全部售单筛除停售和所有权售出以及标签不符合的售单
    List<Sale> finalSaleList = new ArrayList<>();
    for (Sale it : saleList) {

      //  获取work信息（work的标签）
      Work work = workMapper.getWorkById(it.getWorkId());

      //  标签筛选
      boolean judge = true;
      //  work的其中一个标签能够和用户的标签对上就保留
      if (work.getWorkTag1()!=null&&(work.getWorkTag1().equals(userTag1)
          || work.getWorkTag1().equals(userTag2) || work.getWorkTag1().equals(userTag3))) {
        judge = false;
      }
      if (work.getWorkTag2()!=null&&(work.getWorkTag2().equals(userTag1)
          || work.getWorkTag2().equals(userTag2) || work.getWorkTag2().equals(userTag3))) {
        judge = false;
      }
      if (work.getWorkTag3()!=null&&(work.getWorkTag3().equals(userTag1)
          || work.getWorkTag3().equals(userTag2) || work.getWorkTag3().equals(userTag3))) {
        judge = false;
      }

      if(judge) {
        continue;
      }
      finalSaleList.add(it);
    }

    //  如果列表个数小于2,随机选两个
    if(finalSaleList.size()>=2) {
      //  大于两个,清空初始列表
      listForReturn.clear();
      temp = random.nextInt(finalSaleList.size());
      listForReturn.add(finalSaleList.get(temp));
      finalSaleList.remove(temp);
      temp = random.nextInt(finalSaleList.size());
      listForReturn.add(finalSaleList.get(temp));
    }

    List<SaleDTO> saleDTOList = new ArrayList<>();
    for (Sale it : listForReturn) {
      SaleDTO item = new SaleDTO();
      item.setId(it.getId());
      item.setUserId(it.getUserId());
      item.setTitle(it.getTitle());
      int status = it.getStatus();

      switch (status) {
        case 1:
          item.setStatus("使用权");
          break;
        case 2:
          item.setStatus("所有权");
          break;
        default:
          item.setStatus("出错了");
          break;
      }

      item.setPrice(it.getPrice());
      item.setPicture(it.getPicture());
      item.setDescription(it.getDescription());
      Work work = workMapper.getWorkById(it.getWorkId());
      item.setTag1(work.getWorkTag1());
      item.setTag2(work.getWorkTag2());
      item.setTag3(work.getWorkTag3());
      item.setFileName(work.getFileName());
      item.setNftName(work.getWorkName());
      item.setAuthorizeNum(it.getAuthorizeNum());

      int type = work.getType();

      switch (type) {
        case 1:
          item.setType("摄影作品");
          break;
        case 2:
          item.setType("文字作品");
          break;
        case 3:
          item.setType("影视作品");
          break;
        case 4:
          item.setType("音乐作品");
          break;
        case 5:
          item.setType("美术作品");
          break;
        default:
          throw new ServiceException("作品类型错误");
      }
      saleDTOList.add(item);
    }
    return saleDTOList;
  }

  /**
   * 根据用户展示商城商品
   * @param id 用户id
   * @return 展示商品列表
   */
  @Override
  public List<SaleDTO> saleForMall(Integer id) {
    ArrayList<SaleDTO> saleDtoList = new ArrayList<>();
    //  获取全部售单
    List<Sale> saleList = saleMapper.getAllSale();
    for (Sale it : saleList) {
      Integer status = it.getStatus();
      //  跳过该项不加入dtoList,停售的和所有权转让的不加入商城
      if (status == 0 || status == 3) {
        continue;
      }
      //  根据用户id查找交易列表中它买过的商品
      List<Trade> tradeList = tradeMapper.getBuyTrade(id);
      boolean tradeFlag = true;
      for (Trade trade:tradeList) {
        //  买过商品的id和当前商品id相同
        if(trade.getSaleId().equals(it.getId())) {
          //  是买过的商品但是是购买的所有权
          if(trade.getIsOwn()==1) {
            continue;
          }
          tradeFlag = false;
          break;
        }
      }
      //  如果买过该商品则跳过
      if(!tradeFlag) {
        continue;
      }
      //  如果是用户本人的商品则跳过
      if(it.getUserId().equals(id)) {
        continue;
      }
      //  否则展示出来
      SaleDTO item = new SaleDTO();
      item.setId(it.getId());
      item.setTitle(it.getTitle());
      item.setPrice(it.getPrice());
      item.setPicture(it.getPicture());
      item.setAuthorizeNum(it.getAuthorizeNum());
      switch (status) {
        case 1:
          item.setStatus("使用权");
          break;
        case 2:
          item.setStatus("所有权");
          break;
        default:
          item.setStatus("出错了");
          break;
      }
      Work work = workMapper.getWorkById(it.getWorkId());
      String type;
      switch (work.getType()) {
        case 1:
          type = "摄影作品";
          break;
        case 2:
          type = "文字作品";
          break;
        case 3:
          type = "影视作品";
          break;
        case 4:
          type = "音乐作品";
          break;
        case 5:
          type = "美术作品";
          break;
        default:
          throw new ServiceException("作品类型错误");
      }
      //  设置商品的类型
      item.setType(type);

      //  设置标签
      item.setTag1(work.getWorkTag1());
      item.setTag2(work.getWorkTag2());
      item.setTag3(work.getWorkTag3());
      //  设置作品名称
      item.setNftName(work.getWorkName());
      item.setPicture(it.getPicture());
      item.setDescription(it.getDescription());

      saleDtoList.add(item);
    }
    return saleDtoList;
  }


}
